<template>
  <div>
    <el-button
      type="success"
      icon="el-icon-upload"
      size="mini"
      @click="handleUpload"
      v-hasPermi="['system:CompassUniversityInfo:edit']"
    >导入{{title}}
    </el-button>
    <el-dialog
      :title="`导入${title}`"
      :visible.sync="uploadVisible"
      width="600px"
      center
      :show-close="false"
      @close="handleClose"
      >
      <div style="text-align: center">
        <el-upload
          ref="upload"
          drag
          :disabled="isUploading"
          :limit="1"
          :data="{updateSupport: true}"
          accept=".xlsx, .xls"
          :action="base_url + action + '/importData'"
          :headers="headers"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :on-error="onError"
          :auto-upload="false"
          >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
        <div class="btn_wrapoper" style="margin-top: 20px">
          <el-button
            type="success"
            :disabled="isUploading"
            size="mini"
            @click="submitFileForm"
          >开始导入
          </el-button>
          <el-button
            size="mini"
            :disabled="isUploading"
            @click="uploadVisible = false"
          >取消
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { getToken } from "@/utils/auth";
  export default {
    name: "",
    props: {
      title: {
        type: String,
        default: ""
      },
      action: {
        type: String,
        default: ""
      }
    },

    data() {
      return {
        uploadVisible: false,
        headers: { Authorization: "Bearer " + getToken() },
        isUploading: false,
        base_url: process.env.VUE_APP_BASE_API + "/system/"
      }
    },

    methods: {
      handleUpload() {
        this.uploadVisible = true
      },

      handleClose() {
        this.isUploading = false;
        this.$refs.upload.clearFiles();
      },

      handleFileUploadProgress(event, file, fileList) {
        this.isUploading = true;
      },

      handleFileSuccess(response) {
        if (response.code != 200) {
          this.$message({
            message: response.msg,
            type: 'error'
          });
        } else {
          this.$message({
            message: '导入成功！',
            type: 'success'
          });
          this.$emit('success')
        }
        this.uploadVisible = false;
        this.isUploading = false;
        this.$refs.upload.clearFiles();
      },

      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },

      onError() {
        this.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$message({
          message: '导入失败！',
          type: 'error'
        });
      }
    }
  }
</script>

<style scoped>

</style>
